# -*- coding: utf-8 -*-
"""
保温杯中性策略3期 | 邢不行 | 2023分享会
author: 邢不行
微信: xbx6660
"""
import pandas as pd
import numpy as np


def signal(*args):
    df = args[0]
    n = args[1]
    factor_name = args[2]

    # 计算 offset，从纳秒转化为小时
    df['offset'] = df['candle_begin_time'].astype(np.int64) // (10 ** 9) // 3600 % 24

    subs = []
    for offset in range(24):
        # 分别处理每个offset
        df_sub = df[df['offset'] == offset].reset_index(drop=True)
        # 按原有定义计算 PctChange
        df_sub[factor_name] = df_sub['close'].pct_change(n)
        subs.append(df_sub)

    # 合并
    df = pd.concat(subs)

    # 去除多余列
    df.drop(columns=['offset'], inplace=True)

    # 重新排序
    df.sort_values('candle_begin_time', inplace=True, ignore_index=True)
    return df
